<template>
  <el-dialog 
    v-model="visible" 
    title="分享文件" 
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 分享设置表单 -->
    <el-form 
      v-if="!shareResult" 
      :model="shareForm" 
      :rules="shareRules" 
      ref="shareFormRef"
      label-width="100px"
    >
      <!-- 文件信息 -->
      <div class="file-info">
        <el-icon class="file-icon"><Document /></el-icon>
        <div class="file-details">
          <div class="file-name">{{ fileInfo?.originalName || fileInfo?.fileName }}</div>
          <div class="file-size">{{ formatFileSize(fileInfo?.fileSize || 0) }}</div>
        </div>
      </div>

      <el-divider />

      <!-- 分享类型 -->
      <el-form-item label="分享方式" prop="shareType">
        <el-radio-group v-model="shareForm.shareType">
          <el-radio label="PUBLIC">公开分享</el-radio>
          <el-radio label="PASSWORD">密码保护</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 密码设置 -->
      <el-form-item 
        v-if="shareForm.shareType === 'PASSWORD'" 
        label="访问密码" 
        prop="password"
      >
        <el-input 
          v-model="shareForm.password" 
          type="password" 
          placeholder="设置4-20位访问密码"
          show-password 
          maxlength="20"
        />
      </el-form-item>

      <!-- 权限设置 -->
      <el-form-item label="访问权限">
        <el-checkbox-group v-model="permissions">
          <el-checkbox label="preview" :disabled="true">允许预览</el-checkbox>
          <el-checkbox label="download">允许下载</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 分享备注 -->
      <el-form-item label="分享备注">
        <el-input
          v-model="shareForm.description"
          type="textarea"
          placeholder="可选：添加分享说明，告诉访问者分享的原因和内容"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 有效期设置 -->
      <el-form-item label="有效期">
        <el-select v-model="expireType" @change="handleExpireTypeChange" style="width: 120px;">
          <el-option label="永久" value="PERMANENT" />
          <el-option label="7天" value="7_DAYS" />
          <el-option label="30天" value="30_DAYS" />
          <el-option label="自定义" value="CUSTOM" />
        </el-select>
        <el-date-picker
          v-if="expireType === 'CUSTOM'"
          v-model="shareForm.expireTime"
          type="datetime"
          placeholder="选择过期时间"
          style="margin-left: 10px;"
          :disabled-date="disabledDate"
        />
      </el-form-item>

      <!-- 访问次数限制 -->
      <el-form-item label="访问限制">
        <el-checkbox v-model="enableAccessLimit">限制访问次数</el-checkbox>
        <el-input-number
          v-if="enableAccessLimit"
          v-model="shareForm.maxAccessCount"
          :min="1"
          :max="10000"
          style="margin-left: 10px; width: 120px;"
        />
      </el-form-item>
    </el-form>

    <!-- 分享结果展示 -->
    <div v-if="shareResult" class="share-result">
      <div class="result-header">
        <el-icon class="success-icon"><SuccessFilled /></el-icon>
        <span class="success-text">分享创建成功！</span>
      </div>

      <el-divider />

      <!-- 分享链接 -->
      <div class="share-link-section">
        <label class="section-label">分享链接</label>
        <el-input 
          v-model="shareResult.shareUrl" 
          readonly
          class="share-link-input"
        >
          <template #append>
            <el-button @click="copyShareLink" :loading="copying">
              <el-icon><CopyDocument /></el-icon>
              复制
            </el-button>
          </template>
        </el-input>
      </div>

      <!-- 分享信息 -->
      <div class="share-info">
        <div class="info-item">
          <span class="label">分享码:</span>
          <span class="value">{{ shareResult.shareCode }}</span>
        </div>
        <div class="info-item">
          <span class="label">分享方式:</span>
          <span class="value">{{ shareResult.shareType === 'PUBLIC' ? '公开分享' : '密码保护' }}</span>
        </div>
        <div class="info-item" v-if="shareResult.expireTime">
          <span class="label">过期时间:</span>
          <span class="value">{{ formatTime(shareResult.expireTime) }}</span>
        </div>
        <div class="info-item">
          <span class="label">访问次数:</span>
          <span class="value">{{ shareResult.accessCount || 0 }} 次</span>
        </div>
      </div>

      <!-- 使用提示 -->
      <div class="usage-tips">
        <el-alert
          title="分享使用说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <ul>
              <li>复制上方链接发送给需要访问的人</li>
              <li v-if="shareResult.shareType === 'PASSWORD'">访问时需要输入密码: <strong>{{ shareForm.password }}</strong></li>
              <li v-if="shareResult.expireTime">链接将在 {{ formatTime(shareResult.expireTime) }} 过期</li>
              <li v-else>链接永久有效，可随时在分享管理中关闭</li>
            </ul>
          </template>
        </el-alert>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ shareResult ? '关闭' : '取消' }}</el-button>
        <el-button 
          v-if="!shareResult" 
          type="primary" 
          @click="createShare" 
          :loading="loading"
        >
          创建分享
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, SuccessFilled, CopyDocument } from '@element-plus/icons-vue'
import * as shareApi from '@/api/modules/share'
import type { CreateShareRequest, ShareResponse } from '@/api/modules/share'

// Props
interface Props {
  visible: boolean
  fileInfo: any
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'share-created': [share: ShareResponse]
}>()

// Refs
const shareFormRef = ref()
const loading = ref(false)
const copying = ref(false)
const shareResult = ref<ShareResponse | null>(null)

// Form data
const shareForm = reactive<CreateShareRequest>({
  fileId: 0,
  shareType: 'PUBLIC',
  password: '',
  allowDownload: true,
  allowPreview: true,
  expireTime: undefined,
  maxAccessCount: undefined,
  description: ''
})

const permissions = ref(['preview', 'download'])
const expireType = ref('PERMANENT')
const enableAccessLimit = ref(false)

// Computed
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// Form rules
const shareRules = {
  password: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (shareForm.shareType === 'PASSWORD') {
          if (!value || value.length < 4) {
            callback(new Error('密码长度至少4位'))
          } else if (value.length > 20) {
            callback(new Error('密码长度不能超过20位'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// Watch
watch(() => props.fileInfo, (newFileInfo) => {
  if (newFileInfo) {
    shareForm.fileId = newFileInfo.id
  }
}, { immediate: true })

watch(permissions, (newPermissions) => {
  shareForm.allowPreview = newPermissions.includes('preview')
  shareForm.allowDownload = newPermissions.includes('download')
})

watch(enableAccessLimit, (enabled) => {
  if (!enabled) {
    shareForm.maxAccessCount = undefined
  } else {
    shareForm.maxAccessCount = 100
  }
})

// Methods
const handleExpireTypeChange = (type: string) => {
  const now = new Date()
  switch (type) {
    case '7_DAYS':
      shareForm.expireTime = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString()
      break
    case '30_DAYS':
      shareForm.expireTime = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString()
      break
    case 'PERMANENT':
      shareForm.expireTime = undefined
      break
    case 'CUSTOM':
      // 用户手动选择
      break
  }
}

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now()
}

const createShare = async () => {
  try {
    await shareFormRef.value?.validate()

    loading.value = true

    // 准备请求数据，公开分享时不发送密码
    const requestData = { ...shareForm }
    if (requestData.shareType === 'PUBLIC') {
      delete requestData.password
    }

    const response = await shareApi.createShare(requestData)

    shareResult.value = response.data
    emit('share-created', response.data)
    ElMessage.success('分享创建成功')

  } catch (error: any) {
    console.error('创建分享失败:', error)
    ElMessage.error(error.message || '创建分享失败')
  } finally {
    loading.value = false
  }
}

const copyShareLink = async () => {
  if (!shareResult.value) return
  
  try {
    copying.value = true
    const success = await shareApi.copyShareLink(shareResult.value.shareUrl)
    
    if (success) {
      ElMessage.success('分享链接已复制到剪贴板')
    } else {
      ElMessage.error('复制失败，请手动复制')
    }
  } catch (error) {
    ElMessage.error('复制失败')
  } finally {
    copying.value = false
  }
}

const handleClose = () => {
  // 重置表单
  shareResult.value = null
  shareForm.shareType = 'PUBLIC'
  shareForm.password = ''
  shareForm.expireTime = undefined
  shareForm.maxAccessCount = undefined
  shareForm.description = ''
  permissions.value = ['preview', 'download']
  expireType.value = 'PERMANENT'
  enableAccessLimit.value = false

  emit('update:visible', false)
}

const formatFileSize = shareApi.formatFileSize
const formatTime = shareApi.formatTime
</script>

<style scoped lang="scss">
.file-info {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;

  .file-icon {
    font-size: 32px;
    color: #409eff;
    margin-right: 12px;
  }

  .file-details {
    .file-name {
      font-weight: 500;
      color: #303133;
      margin-bottom: 4px;
    }

    .file-size {
      font-size: 12px;
      color: #909399;
    }
  }
}

.share-result {
  .result-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .success-icon {
      font-size: 20px;
      color: #67c23a;
      margin-right: 8px;
    }

    .success-text {
      font-weight: 500;
      color: #67c23a;
    }
  }

  .share-link-section {
    margin-bottom: 16px;

    .section-label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #303133;
    }

    .share-link-input {
      :deep(.el-input__inner) {
        font-family: monospace;
        font-size: 12px;
      }
    }
  }

  .share-info {
    .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .label {
        color: #909399;
      }

      .value {
        color: #303133;
        font-weight: 500;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
